<template>
  <div class="app-container page-wood-sales-note">
    <el-row :gutter="10" class="sumbit-btn-group mb8">
      <template v-if="!allocatingId">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
           @click="saveHandleAdd"
            v-hasPermi="['allocating:order:add']"
            >保存并新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            @click="submitForm"
            v-hasPermi="['allocating:order:add']"
            >保存</el-button
          >
        </el-col>
      </template>
      <template v-else>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="newAddSell"
            v-hasPermi="['allocating:order:add']"
            >新增</el-button
          >
        </el-col>
        <template>
          <el-col :span="1.5">
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              @click="setAuditStatus"
              v-hasPermi="['allocating:order:edit']"
              >{{ form.auditStatus == 0 ? "审核" : "反审核" }}</el-button
            >
          </el-col>
        </template>
        <template>
          <el-col :span="1.5" v-if="form.auditStatus != 1">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              @click="submitForm(1)"
              v-hasPermi="['allocating:order:edit']"
              >保存</el-button
            >
          </el-col>
        </template>
      </template>
    </el-row>

    <div class="table-area">
      <el-form
        :model="form"
        ref="form" 
        :inline="true"
        v-show="showSearch"
        :rules="rules"
        label-width="90px"
      >
        <el-form-item label="供应商" prop="supplierName">
          <SupplierSelect
            v-model="form.supplierName"
            placeholder="请输入供应商"
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item label="客户" prop="customerName">
          <SupplierSelect
            :typeSelect="customer"
            v-model="form.customerName"
            placeholder="请输入客户"
            :disabled="disabled"
          />
        </el-form-item>

        <el-form-item label="单据日期" prop="billTime">
          <el-date-picker
            clearable
            size="small"
            v-model="form.billTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择单据日期"
            :disabled="disabled"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="单据编号" prop="allocatingId">
          <el-input
            v-model="form.allocatingId"
            placeholder="请输入单据编号"
            :disabled="true"
            size="small"
          />
        </el-form-item>

        <el-form-item label="销售员" prop="salesName">
          <SupplierSelect
            :typeSelect="sales"
            v-model="form.salesName"
            placeholder="请输入销售员"
            :disabled="disabled"
          />
        </el-form-item>

        <el-form-item label="税率(%)" prop="taxRate">
          <el-input-number
            v-model="form.taxRate"
            controls-position="right"
            :min="0"
            :max="100"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="车号" prop="carNo">
          <el-input
            v-model="form.carNo"
            placeholder="请输入车号"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <!-- 表格开始 -->
        <TableForm
          ref="TableForm"
          :column="getSalesTableData"
          :list="form.woodAllocatingOrderGoodsList"
          :loading="loading"
     
       />
        <!-- 表格结束 -->

        <!-- 备注信息 -->
        <el-form-item class="form-remark" prop="remark">
          <el-input
            type="textarea"
            placeholder="请输入备注信息"
            v-model="form.remark"
            clearable
            size="small"
            rows="5"
          />
        </el-form-item>
        <img v-if="form.auditStatus == 1" :src="img.audit" class="img-audit" />
      </el-form>
    </div>

  </div>
</template>

<script>
import SupplierSelect from "@/components/SupplierSelect";
import CellInput from "@/components/CellInput";
import TableForm from "@/components/TableForm/preset";
import SearchInput from "@/components/SearchInput";

export default {
  name: "allocaing",
  components: {
    SupplierSelect,
    CellInput,
    TableForm,
    SearchInput,
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 导出遮罩层
      exportLoading: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
 
      // 组件替换条件
      customer: "customerName",
      sales: "nickName",

      form: {
        allocatingId: "",
        isStatus: "0",
        auditStatus: 0,
        ids: [],
        // 调货单信息表格数据
        woodAllocatingOrderGoodsList: [
          {
            goodsName: "", // 品名
            brandName: "", // 品牌
            level: "", //等级
            warehouse: "", // 仓库
            ply: 0, // 厚度
            width: 0, // 宽度
            length: 0, // 长度
            sliceCount: 0, // 片数
            pieceCount: 0, // 件数
            count: 0, // 方数
            oneCount: 0, //单包方数
            salesPrice: 0, //销售单价
            salesMoney: 0,
            purchaseMoney: 0,
            purchasePrice: 0,
            money: 0, // 金额
            goodsStatus: "", // 货物状态
            pactName: "", //开证公司
            remark: "", // 备注
            taxRate: "",
            gcountId: "",
          },
        ],
      },
      // 表单校验
      rules: {
        customerName: [
          {
            required: true,
            message: "客户不能为空",
            trigger: "blur",
          },
        ],
        billTime: [
          {
            required: true,
            message: "单据日期不能为空",
            trigger: "blur",
          },
        ],
        orderId: [
          {
            required: true,
            message: "订单号不能为空",
            trigger: "blur",
          },
        ],
        salesName: [
          {
            required: true,
            message: "销售员不能为空",
            trigger: "blur",
          },
        ],
        carNo: [
          {
            required: true,
            message: "车号不能为空",
            trigger: "blur",
          },
        ],
      },
      // 表格参数
      getSalesTableData: [
        {label: "品名"},
        {label: "品牌"},
        {label: "等级"},
        {label: "仓库"},
        {label: "厚度(mm)"},
        {label: "宽度(mm)"},
        {label: "长度(m)"},
        {label: "片数"},
        {label: "件数"},
        {label: "单包方数"},
        {label: "方数", inputType: "none",value:'count',sync:'inCount'},
        {
          width:"130",
          label: "采购单价(批量)",
          value: "purchasePrice",
          inputType: "number",
          decimal: 3,
          onchange: this.moneyCount,
          rules: [
            {
              min: 0.01,
              type: "number",
              message: "请输入采购单价",
              trigger: "blur",
            },
          ],
        },
        {
          label: "采购金额",
          value: "purchaseMoney",
          inputType: "none",
          summary: true,
        },
        {
          width:"130",
          label: "销售单价(批量)",
          value: "salesPrice",
          inputType: "number",
          decimal: 3,
          onchange: this.moneyCount,
          rules: [
            {
              min: 0.01,
              type: "number",
              message: "请输入销售单价",
              trigger: "blur",
            },
          ],
        },
        {
          label: "销售金额",
          value: "salesMoney",
          inputType: "none",
          summary: true,
        },
        { label: "备注(批量)" },
      ],
      // 业务员
      salesman: null,
      //调货单号
      allocatingId: "",

      img: {
        audit: require("@/assets/images/bg@audit.png"),
      },
    };
  },
  created() {
    let { id } = this.$route.params;
    this.allocatingId = id;
    id && this.getallocatingIdDetail();

    if (this.form.allocatingId == null || this.allocatingId == null) {
      this.$Api.onlyId.getId().then((res) => {
        let { data } = res;
        this.form.allocatingId = data;
      });
    }
  },
  computed: {
    disabled() {
      if (this.form.auditStatus == 1) {
        return !!this.orderId;
      }
    },
  },
  watch:{
      
    },
  methods: {

    // 金额计算 ： 单价 * 方数
    moneyCount(d) {
      let { inCount, purchasePrice, purchaseMoney, salesPrice, salesMoney} = d;
      let t = ((purchasePrice || 0) * (inCount || 0)).toFixed(3);
      let m = ((salesPrice || 0) * (inCount || 0)).toFixed(3);
      this.purchasePrice = purchasePrice;
      this.salesPrice = salesPrice;
      d.purchaseMoney = t;
      d.salesMoney = m;
    },

    // 获取详情
    getallocatingIdDetail() {
      let { allocatingId } = this;
      this.$Api.sales.allocating.detail(allocatingId).then((res) => {
        let { data, code } = res;
        if (code === 200) {
          this.form = data;
        }
      });
    },

    // 取消按钮
    cancel() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.dialogTable = false;
          this.open = false;
        }
      });
    },
    // 表格重置
    reset() {
      this.form ={
        allocatingId: null,
        woodAllocatingOrderGoodsList : [
            {
            goodsName: null, // 品名
            brandName: null, // 品牌
            level: null, //等级
            warehouse: null, // 仓库
            ply: null, // 厚度
            width: null, // 宽度
            length: null, // 长度
            sliceCount: null, // 片数
            pieceCount: null, // 件数
            inCount: null, // 方数
            oneCount: null, //单包方数
            salesPrice: 0, //销售单价
            salesMoney: 0,
            purchaseMoney: 0,
            purchasePrice: 0,
            money: null, // 金额
            goodsStatus: null, // 货物状态
            pactName: null, //开证公司
            remark: null, // 备注
            },
        ]
      }
      
    },
 
    /** 保存提交按钮  方数对比*/
    submitForm(state) {
      let { taxRate, woodAllocatingOrderGoodsList } = this.form;

      woodAllocatingOrderGoodsList.forEach((item, index) => {
        item.taxRate = taxRate;
        item.gcountId;
        // item.count = item.inCount;
      });
 
        this.$refs["form"].validate((pass, error) => {
          pass &&
            this.$refs["TableForm"].checkForm((TableFormPass, error) => {
              if (TableFormPass) {
                  if( state != 1){
                    this.$Api.sales.allocating.add(this.form).then((res) => {
                    if (res.code == 200) {
                      this.allocatingId = res.data;
                      this.msgSuccess("操作成功");
                      const id = this.allocatingId;
                      let path = `/allocating/list/${id}`;
                      this.$router.push({
                        path,
                      });
                    } else {
                      this.$message.error("操作失败");
                    }
                  }).catch( ()=>{})
                } else{
                    this.$Api.sales.allocating.edit(this.form).then((res) => {
                      let { code, data } = res;
                    if (code == 200) {
                      this.allocatingId = data;
                      this.getallocatingIdDetail(data);
                      this.msgSuccess("操作成功");
                    } else {
                      this.$message.error("操作失败");
                    }
                  }).catch( ()=>{})
                }
              } 
            });
        });
      },
    //保存并新增
    saveHandleAdd() {
      this.submitForm();
      this.reset();

    },
    // 新增
    newAddSell() {
      this.$router.push({ path: "/sale/receipts/allocating" });
      this.reset();
    },
    // 审核与反审核 审核状态;0未审核 1已审核
    setAuditStatus() {
      let { allocatingId } = this;
      let { auditStatus } = this.form;

      this.$confirm(
        "是否确认" +
          `${auditStatus == 0 ? "审核" : "反审核"}` +
          '采购订单信息编号为"' +
          allocatingId +
          '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          let nextAudit = auditStatus == 1 ? 0 : 1;
          this.$Api.sales.allocating
            .setState({
              ids:[allocatingId],
              auditStatus:nextAudit
            })
            .then((res) => {
              if (res.code == 200) {
                this.getallocatingIdDetail();
                this.msgSuccess("审核成功");
              } else {
                this.$message.error("审核失败");
              }
            })
            .catch(() => {});
        })
       },
    },
    
};
</script>

<style lang="scss" scoped>
::v-deep.page-wood-sales-note {
  .img-audit {
    position: absolute;
    right: 30px;
    bottom: 30px;
    transform: rotate(-18deg);
    pointer-events: none;
  }
  .sumbit-btn-group {
    margin: 0 0 20px 0;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    .empty {
      width: 100%;
      flex: 1;
    }
  }
  .btn-group {
    display: flex;
    align-items: center;
    justify-content: space-evenly;
  }

  .disabled {
    color: #a8a8a8;
  }

  .error {
    color: #fa3e3e;
  }

  .form-remark {
    display: grid;
    margin: 20px 15px 15px;
    .el-form-item__contentt {
      display: inline-block;
      width: 100%;
    }
  }
}
</style>
